<template>
  <view class="bg-gray-50 w-[750rpx] pb-[100rpx] box-border" >
    <!-- 用户信息头部 -->
    <PageHeader title="我的推广" :showBack="true" />
    <!-- <view
      class="bg-gradient-to-r from-purple-600 to-blue-500 text-white p-[40rpx] rounded-b-[40rpx] shadow-lg"
    >
      <view class="flex items-center mb-[30rpx]">
        <view
          class="w-[120rpx] h-[120rpx] rounded-full border-4 border-white border-opacity-30 bg-white overflow-hidden mr-[30rpx]"
        >
          <image
            src="https://via.placeholder.com/120x120/2575fc/ffffff?text=头像"
            class="w-full h-full object-cover"
          />
        </view>
        <view class="flex-1">
          <view class="text-[40rpx] font-bold mb-[10rpx] flex items-center">
            <text>张推广达人</text>
            <view
              class="bg-gradient-to-r from-yellow-400 to-yellow-600 text-yellow-800 px-[15rpx] py-[5rpx] rounded-[20rpx] text-[24rpx] font-bold ml-[15rpx]"
            >
              SVIP会员
            </view>
          </view>
          <text class="text-[28rpx] opacity-90">ID: 888888</text>
        </view>
      </view>

      <view
        class="bg-white bg-opacity-15 rounded-[20rpx] p-[25rpx] flex justify-between items-center"
      >
        <view class="text-center">
          <text class="text-[26rpx] opacity-80 block mb-[10rpx]"
            >可提现奖励</text
          >
          <text class="text-[40rpx] font-bold">¥ 1,568.50</text>
        </view>
        <nut-button
          type="primary"
          size="small"
          class="bg-white text-blue-500 px-[40rpx] py-[15rpx] rounded-[50rpx] text-[28rpx] font-bold"
          @click="handleWithdraw"
        >
          提现到微信
        </nut-button>
      </view>
    </view> -->
    <!-- 返回按钮 -->
   

    <!-- 推广二维码卡片 -->
    <view class="bg-white rounded-[25rpx] p-[30rpx] m-[30rpx] shadow-lg">
      <view
        class="flex justify-between items-center mb-[30rpx] pb-[20rpx] border-b border-gray-100"
        :style="{textAlign: 'center',width:'100%',display:'block'}"
      >
        <text class="text-[34rpx] font-bold text-gray-800" >我的推广二维码</text>
        <IconFont name="qrcode" class="text-blue-500 text-[40rpx]" />
      </view>

      <view class="text-center py-[20rpx]">
        <!-- 隐藏的Canvas用于生成二维码 -->
        <canvas 
          :canvas-id="canvasId"
          style="position: absolute; left: -9999px; width: 300px; height: 300px;"
        />
        <!-- 备用Canvas -->
        <canvas 
          canvas-id="qrcode-canvas-backup"
          style="position: absolute; left: -9999px; width: 300px; height: 300px;"
        />
        
        <view
          class="w-[350rpx] h-[350rpx] mx-auto bg-gray-50 rounded-[20rpx] flex items-center justify-center relative"
        >
          <!-- 二维码图片 -->
          <image 
            v-if="qrCodeDataUrl"
            :src="qrCodeDataUrl"
            class="w-[300rpx] h-[300rpx] rounded-[10rpx]"
            mode="aspectFit"
          />
          <!-- 加载中状态 -->
          <view v-else class="flex flex-col items-center justify-center">
            <IconFont name="loading" class="text-blue-500 text-[60rpx] animate-spin mb-[20rpx]" />
            <text class="text-[28rpx] text-gray-500">{{ isGeneratingQR ? '生成二维码中...' : '二维码加载中...' }}</text>
          </view>
          <!-- 中心Logo -->
          <!-- <view
            class="absolute w-[70rpx] h-[70rpx] bg-white rounded-[10rpx] flex items-center justify-center text-[30rpx] text-blue-500 shadow-md"
          >
            <IconFont name="crown" />
          </view> -->
        </view>
        <text class="mt-[25rpx] text-[28rpx] text-gray-600 block"
          >扫码注册成为您的专属会员</text
        >
        <!-- 推广链接显示 -->
        <view class="mt-[20rpx] p-[20rpx] bg-gray-50 rounded-[15rpx]">
          <text class="text-[24rpx] text-gray-500 block mb-[10rpx]">推广链接：</text>
          <text class="text-[26rpx] text-blue-500 break-all">{{ promotionUrl }}</text>
        </view>
      </view>

      <view class="flex justify-between mt-[40rpx] gap-x-[20rpx]">
        <nut-button
          type="default"
          size="large"
          class="flex-1 mr-[10rpx] bg-blue-50 text-blue-500 border-blue-500"
          @click="handleCopyLink"
        >
        <template #icon>
          <IconFont name="link" class="mr-[10rpx]" />
        </template>
          
          复制推广链接
        </nut-button>
        <nut-button
          type="primary"
          size="large"
          class="flex-1 ml-[10rpx] bg-blue-500"
          @click="handleSaveQR"
        >
        <template #icon>
          <IconFont name="download" class="mr-[10rpx]" />
        </template>
          保存二维码
        </nut-button>
      </view>
      
      <!-- 重新生成二维码按钮 -->
      <!-- <view class="mt-[20rpx]">
        <nut-button
          type="default"
          size="normal"
          class="w-full bg-gray-50 text-gray-600 border-gray-300"
          @click="handleRegenerateQR"
        >
        <template #icon>
          <IconFont name="refresh" class="mr-[10rpx]" />
        </template>
          重新生成二维码
        </nut-button>
      </view> -->
    </view>

    <!-- 推广说明 -->
    <view class="bg-white rounded-[25rpx] p-[30rpx] m-[30rpx] shadow-lg promotion-tips">
      <view class="mb-[20rpx] pb-[10rpx] border-b border-gray-100">
        <text class="text-[32rpx] font-bold text-gray-800">推广说明要点</text>
      </view>
      <view class="tip-list">
        <view class="tip-item text-[28rpx] text-gray-700 mb-[12rpx]">1. 每成功邀请一位新用户注册并完成首单，可获得奖励。</view>
        <view class="tip-item text-[28rpx] text-gray-700 mb-[12rpx]">2. 推广链接请勿恶意刷量，否则将取消奖励资格。</view>
        <view class="tip-item text-[28rpx] text-gray-700 mb-[12rpx]">3. 奖励将在用户完成任务后自动发放至账户。</view>
        <view class="tip-item text-[28rpx] text-gray-700 mb-[12rpx]">4. 可在"推广统计中心"随时查看推广数据和奖励明细。</view>
        <view class="tip-item text-[28rpx] text-gray-700">5. 如有疑问请联系客服。</view>
      </view>
    </view>

    <!-- 推广数据卡片 -->
    <!-- <view class="bg-white rounded-[25rpx] p-[30rpx] m-[30rpx] shadow-lg">
      <view class="flex justify-between items-center mb-[30rpx] pb-[20rpx] border-b border-gray-100">
        <text class="text-[34rpx] font-bold text-gray-800">推广数据统计</text>
        <IconFont name="chart-line" class="text-blue-500 text-[40rpx]" />
      </view>
      
      <view class="grid grid-cols-3 gap-[20rpx]">
        <view class="bg-gray-50 rounded-[20rpx] p-[25rpx] text-center">
          <text class="text-[40rpx] font-bold text-blue-500 mb-[10rpx] block">128</text>
          <text class="text-[26rpx] text-gray-600">总推广会员</text>
        </view>
        <view class="bg-gray-50 rounded-[20rpx] p-[25rpx] text-center">
          <text class="text-[40rpx] font-bold text-blue-500 mb-[10rpx] block">86</text>
          <text class="text-[26rpx] text-gray-600">已消费会员</text>
        </view>
        <view class="bg-gray-50 rounded-[20rpx] p-[25rpx] text-center">
          <text class="text-[40rpx] font-bold text-blue-500 mb-[10rpx] block">42</text>
          <text class="text-[26rpx] text-gray-600">未消费会员</text>
        </view>
      </view>
    </view> -->

    <!-- 分销数据卡片 -->
    <!-- <view class="bg-white rounded-[25rpx] p-[30rpx] m-[30rpx] shadow-lg">
      <view class="flex justify-between items-center mb-[30rpx] pb-[20rpx] border-b border-gray-100">
        <text class="text-[34rpx] font-bold text-gray-800">推广奖励明细</text>
        <IconFont name="money-bill-wave" class="text-blue-500 text-[40rpx]" />
      </view>
      
      <view class="space-y-[30rpx]">
        <view 
          v-for="(item, index) in rewardData" 
          :key="index"
          class="flex justify-between py-[25rpx] border-b border-gray-100"
        >
          <text class="text-gray-600">{{ item.label }}</text>
          <text class="font-bold text-gray-800">{{ item.value }}</text>
        </view>
      </view>
    </view> -->

    <!-- 平台扣点卡片 -->
    <!-- <view class="bg-white rounded-[25rpx] p-[30rpx] m-[30rpx] shadow-lg">
      <view class="flex justify-between items-center mb-[30rpx] pb-[20rpx] border-b border-gray-100">
        <text class="text-[34rpx] font-bold text-gray-800">平台扣点比例</text>
        <IconFont name="percent" class="text-blue-500 text-[40rpx]" />
      </view>
      
      <view class="flex justify-between">
        <view class="bg-gray-50 rounded-[20rpx] p-[30rpx] w-[48%] text-center">
          <text class="text-[32rpx] font-bold mb-[15rpx] block">普通会员</text>
          <text class="text-[48rpx] font-bold text-red-500 mb-[20rpx] block">15%</text>
          <text class="text-[26rpx] text-gray-600 mb-[20rpx] block">平台信息服务费比例</text>
        </view>
        
        <view class="bg-gray-50 rounded-[20rpx] p-[30rpx] w-[48%] text-center">
          <text class="text-[32rpx] font-bold mb-[15rpx] block">SVIP会员</text>
          <text class="text-[48rpx] font-bold text-red-500 mb-[20rpx] block">5%</text>
          <text class="text-[26rpx] text-gray-600 mb-[20rpx] block">平台信息服务费比例</text>
          <nut-button 
            type="warning" 
            size="small"
            class="w-full text-[28rpx] font-bold"
            @click="handleUpgrade"
          >
            立即升级
          </nut-button>
        </view>
      </view>
    </view> -->

    <!-- 底部导航 -->
    <!-- <view class="fixed bottom-0 left-0 w-[750rpx] bg-white flex justify-around py-[20rpx] shadow-lg z-100">
      <view 
        v-for="(nav, index) in navItems" 
        :key="index"
        class="flex flex-col items-center text-[24rpx]"
        :class="nav.active ? 'text-blue-500' : 'text-gray-400'"
        @click="handleNavClick(nav.name)"
      >
        <IconFont :name="nav.icon" class="text-[40rpx] mb-[8rpx]" />
        <text>{{ nav.name }}</text>
      </view>
    </view> -->
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
import PageHeader from '@/components/PageHeader.vue'
import { useUserStore } from '@/store/user'
// @ts-ignore
import QRCode from 'qrcode-generator'

/**
 * 推广页面组件
 * 显示用户推广二维码、推广链接和相关说明
 */
const userStore = useUserStore()

// 二维码数据URL
const qrCodeDataUrl = ref<string>('')

// 二维码生成状态
const isGeneratingQR = ref<boolean>(false)

// 二维码生成错误状态
const qrCodeError = ref<string>('')

// Canvas ID，确保唯一性
const canvasId = ref<string>('qrcode-canvas-' + Date.now())

// 推广链接
const promotionUrl = computed(() => {
  const recommendCode = userStore.userInfo.recommend_code || 'jsz'
  console.log("recommendCode", recommendCode)
  if (!recommendCode) {
    return '请先完善个人信息获取推广码'
  }
  // 获取当前域名，如果没有则使用默认域名
  const currentDomain = Taro.getSystemInfoSync().platform === 'devtools' 
    ? 'https://nengliguangchang.suchi.hongyutiancheng.com'
    : window.location.origin
  return `${currentDomain}?recommend=${recommendCode}`
})

/**
 * 生成二维码
 * 使用qrcode-generator库生成包含推广链接的二维码
 */
const generateQRCode = async () => {
  console.log("generateQRCode")
  try {
    isGeneratingQR.value = true
    const url = promotionUrl.value
    console.log("url", url)
    if (!url || url.includes('请先完善')) {
      Taro.showToast({
        title: '请先完善个人信息获取推广码',
        icon: 'none'
      })
      return
    }

    // 使用qrcode-generator生成二维码
    const qr = QRCode(0, 'M') // 错误纠正级别M，适合大多数场景
    qr.addData(url)
    qr.make()
    
    // 获取二维码数据
    const moduleCount = qr.getModuleCount()
    const canvasSize = 300
    const cellSize = Math.floor(canvasSize / moduleCount)
    const padding = Math.floor((canvasSize - moduleCount * cellSize) / 2)
    
    // 确保Canvas元素存在
    await new Promise(resolve => setTimeout(resolve, 100))
    
    // 创建Canvas上下文
    let canvas
    try {
      canvas = Taro.createCanvasContext(canvasId.value)
      if (!canvas) {
        throw new Error('Canvas上下文创建失败')
      }
    } catch (error) {
      console.error('Canvas上下文创建失败:', error)
      // 尝试使用备用Canvas ID
      try {
        canvas = Taro.createCanvasContext('qrcode-canvas-backup')
        if (!canvas) {
          throw new Error('备用Canvas也创建失败')
        }
      } catch (backupError) {
        console.error('备用Canvas创建也失败:', backupError)
        throw new Error('Canvas初始化失败')
      }
    }
    
    // 清空画布并设置白色背景
    canvas.clearRect(0, 0, canvasSize, canvasSize)
    canvas.setFillStyle('#FFFFFF')
    canvas.fillRect(0, 0, canvasSize, canvasSize)
    
    // 绘制二维码
    canvas.setFillStyle('#000000')
    
    for (let row = 0; row < moduleCount; row++) {
      for (let col = 0; col < moduleCount; col++) {
        if (qr.isDark(row, col)) {
          canvas.fillRect(
            padding + col * cellSize, 
            padding + row * cellSize, 
            cellSize, 
            cellSize
          )
        }
      }
    }
    
    // 绘制到Canvas
    canvas.draw(false, () => {
      setTimeout(() => {
        // 将Canvas转换为图片，设置高质量
        Taro.canvasToTempFilePath({
          canvasId: canvasId.value,
          width: canvasSize,
          height: canvasSize,
          destWidth: canvasSize * 2, // 2倍分辨率，提高清晰度
          destHeight: canvasSize * 2,
          fileType: 'png',
          quality: 1,
          success: (res) => {
            qrCodeDataUrl.value = res.tempFilePath
            isGeneratingQR.value = false
            qrCodeError.value = '' // 清除错误状态
            console.log('二维码生成成功:', res.tempFilePath)
          },
          fail: (error) => {
            console.error('Canvas转图片失败:', error)
            // 尝试使用备用Canvas ID
            Taro.canvasToTempFilePath({
              canvasId: 'qrcode-canvas-backup',
              width: canvasSize,
              height: canvasSize,
              destWidth: canvasSize * 2,
              destHeight: canvasSize * 2,
              fileType: 'png',
              quality: 1,
              success: (res) => {
                qrCodeDataUrl.value = res.tempFilePath
                isGeneratingQR.value = false
                qrCodeError.value = ''
                console.log('二维码生成成功(备用):', res.tempFilePath)
              },
              fail: (backupError) => {
                console.error('备用Canvas转图片也失败:', backupError)
                isGeneratingQR.value = false
                qrCodeError.value = 'Canvas转图片失败'
                Taro.showToast({
                  title: '生成二维码失败',
                  icon: 'none'
                })
              }
            })
          }
        })
      }, 500) // 增加延迟确保Canvas绘制完成
    })
  } catch (error) {
    console.error('生成二维码错误:', error)
    isGeneratingQR.value = false
    qrCodeError.value = '生成二维码失败'
    Taro.showToast({
      title: '生成二维码失败',
      icon: 'none'
    })
  }
}

// 返回上一页
const goBack = () => {
  Taro.navigateBack({
    delta: 1,
  });
};

// 奖励数据
const rewardData = ref([
  { label: "直接推荐会员", value: "86人" },
  { label: "团队会员总数", value: "243人" },
  { label: "团队消费总额", value: "¥ 86,420.50" },
  { label: "累计奖励金额", value: "¥ 3,856.80" },
  { label: "本月预估收益", value: "¥ 1,245.60" },
]);

// 底部导航
const navItems = ref([
  { name: "首页", icon: "home", active: false },
  { name: "团队", icon: "users", active: false },
  { name: "我的", icon: "user", active: true },
  { name: "钱包", icon: "wallet", active: false },
  { name: "设置", icon: "cog", active: false },
]);

// 提现
const handleWithdraw = () => {
  Taro.showToast({
    title: "提现申请已提交，将在1-3个工作日内到账",
    icon: "success",
  });
};

// 复制推广链接
const handleCopyLink = () => {
  const url = promotionUrl.value
  if (url.includes('请先完善')) {
    Taro.showToast({
      title: '请先完善个人信息获取推广码',
      icon: 'none'
    })
    return
  }
  
  Taro.setClipboardData({
    data: url,
    success: () => {
      Taro.showToast({
        title: "推广链接已复制到剪贴板",
        icon: "success",
      });
    },
  });
};

// 保存二维码
const handleSaveQR = () => {
  if (!qrCodeDataUrl.value) {
    Taro.showToast({
      title: '二维码生成中，请稍候',
      icon: 'none'
    })
    return
  }
  
  Taro.saveImageToPhotosAlbum({
    filePath: qrCodeDataUrl.value,
    success: () => {
      Taro.showToast({
        title: "推广二维码已保存到相册",
        icon: "success",
      });
    },
    fail: () => {
      Taro.showToast({
        title: "保存失败，请检查相册权限",
        icon: "none",
      });
    }
  });
};

// 重新生成二维码
const handleRegenerateQR = () => {
  if (isGeneratingQR.value) {
    Taro.showToast({
      title: '二维码正在生成中，请稍候',
      icon: 'none'
    })
    return
  }
  
  // 重置Canvas ID
  canvasId.value = 'qrcode-canvas-' + Date.now()
  qrCodeDataUrl.value = '' // 清空当前二维码
  qrCodeError.value = '' // 清除错误状态
  
  // 强制重新渲染Canvas元素
  nextTick(() => {
    setTimeout(() => {
      generateQRCode()
    }, 200)
  })
};

// 升级会员
const handleUpgrade = () => {
  Taro.showToast({
    title: "正在跳转SVIP会员升级页面",
    icon: "none",
  });
};

// 导航点击
const handleNavClick = (name: string) => {
  navItems.value.forEach((item) => {
    item.active = item.name === name;
  });

  Taro.showToast({
    title: `切换到${name}`,
    icon: "none",
  });
};

// 页面加载时生成二维码
onMounted(async () => {
  try {
    // 确保用户信息已加载
    if (!userStore.userInfo.recommend_code) {
      await userStore.fetchUserInfo()
    }
    
    // 检查是否有推荐码
    if (userStore.userInfo.recommend_code) {
      generateQRCode()
    } else {
      Taro.showToast({
        title: '请先完善个人信息获取推广码',
        icon: 'none',
        duration: 2000
      })
    }
  } catch (error) {
    console.error('初始化推广页面失败:', error)
    Taro.showToast({
      title: '页面加载失败，请重试',
      icon: 'none'
    })
  }
})
</script>
